package com.xidian.zhiancloud.service.dangerWorkTicket.WorkApprove;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xidian.zhiancloud.dao.UnsafeWorkApproveMapper;
import com.xidian.zhiancloud.dao.syset.SysPositionMapper;
import com.xidian.zhiancloud.dao.syset.SysUserMapper;
import com.xidian.zhiancloud.dao.syset.usermanage.OrganizationMapper;
import com.xidian.zhiancloud.dao.workTicket.WorkTicketMapper;
import com.xidian.zhiancloud.dao.workTicket.WorkTicketTemplateMapper;
import com.xidian.zhiancloud.enums.GeneralResponseEnums;
import com.xidian.zhiancloud.exception.CustomizeException;
import com.xidian.zhiancloud.model.UnsafeWorkApprove;
import com.xidian.zhiancloud.model.syset.Organization;
import com.xidian.zhiancloud.model.syset.SysPosition;
import com.xidian.zhiancloud.model.syset.SysUser;
import com.xidian.zhiancloud.model.dangerWorkTicket.WorkTicket;
import com.xidian.zhiancloud.model.dangerWorkTicket.WorkTicketTemplate;
import com.xidian.zhiancloud.qo.dangerWorkTicket.WorkTicketQO;
import com.xidian.zhiancloud.vo.dangerWorkTicket.UnsafeWorkApproveDTOVO;
import com.xidian.zhiancloud.vo.dangerWorkTicket.UnsafeWorkApproveVO;
import com.xidian.zhiancloud.vo.dangerWorkTicket.WorkTicketVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.LinkedList;
import java.util.List;

@Service
public class UnsafeWorkApproveService extends ServiceImpl<UnsafeWorkApproveMapper, UnsafeWorkApprove> implements IService<UnsafeWorkApprove> {
    @Autowired
    private UnsafeWorkApproveMapper unsafeWorkApproveMapper;

    @Autowired
    private WorkTicketMapper workTicketMapper;

    @Autowired
    private SysPositionMapper sysPositionMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private OrganizationMapper organizationMapper;

    @Autowired
    private WorkTicketTemplateMapper workTicketTemplateMapper;

    public IPage<WorkTicketVO> getListByQO(WorkTicketQO workTicketQO){                // 分页
        Page<WorkTicketVO> page = new Page<>(workTicketQO.getCurrent(), workTicketQO.getSize());
        OrderItem orderedItem = new OrderItem();
        orderedItem.setColumn("create_time").setAsc(false);
        page.getOrders().add(orderedItem);
        IPage<WorkTicketVO> res = unsafeWorkApproveMapper.getListByQO(page, workTicketQO);
        // 联表查询
        res.getRecords().forEach(
                vo -> {
                    Long ticketType = vo.getTicketType();
                    WorkTicketTemplate template = workTicketTemplateMapper.selectById(ticketType);
                    vo.setWorkTemplateName(
                            template == null ? "作业票类型已删除" : template.getName()
                    );
                    SysPosition position = sysPositionMapper.selectById(vo.getPositionId());
                    vo.setLocationName(position == null ? "该位置不存在" : position.getName());
                }
        );
        // 获取位置string

        return res;
    }



    /**
     * 根据作业票id，查找作业票，以及相关的审批结果
     *
     * @param id
     * @return
     */
    public UnsafeWorkApproveDTOVO getById(Long id) {
        // 判断相应id的作业票是否存在
        WorkTicket workTicket = workTicketMapper.selectById(id);
        if (workTicket == null) {
            throw new CustomizeException(GeneralResponseEnums.SYSTEM_ERROR);
        }

        // 修改为Mybatis Plus的查询条件
        LambdaQueryWrapper<UnsafeWorkApprove> query = Wrappers.<UnsafeWorkApprove>lambdaQuery();
        query.eq(UnsafeWorkApprove::getRelateWorkId, id);
        List<UnsafeWorkApprove> unsafeWorkApproves = unsafeWorkApproveMapper.selectList(query);

        // long字段转为String显示
        UnsafeWorkApproveDTOVO res = new UnsafeWorkApproveDTOVO();
        WorkTicketVO vo = new WorkTicketVO();
        BeanUtils.copyProperties(workTicket, vo);
        SysUser applicant = sysUserMapper.selectById(vo.getCreatorId());
        vo.setCreatorName(applicant == null ? "该用户不存在" : applicant.getName());
        SysPosition position = sysPositionMapper.selectById((vo.getPositionId()));
        vo.setLocationName(position == null ? "该位置不存在" : position.getName());
        res.setWorkTicketVO(vo);

        // 展示审批历史记录表t_unsafe_work_approve
        List<UnsafeWorkApproveVO> voList = returnApproveRecord(id, unsafeWorkApproves);

        res.setUnsafeWorkApproveVOList(voList);

        return res;
    }


    /**
     * 返回审批历史记录表t_unsafe_work_approve的信息
     */
    public List<UnsafeWorkApproveVO> returnApproveRecord(Long id, List<UnsafeWorkApprove> unsafeWorkApproves) {
        List<UnsafeWorkApproveVO> voList = new LinkedList<>();
        for (int i = 0; i < unsafeWorkApproves.size(); i++) {
            UnsafeWorkApprove approves= unsafeWorkApproves.get(i);
            // 获取审批记录表中与id相关的记录
            System.out.println("id = " + id + " 的作业票关联的审批结果有：" + approves);
            UnsafeWorkApproveVO vos = new UnsafeWorkApproveVO();
            BeanUtils.copyProperties(unsafeWorkApproves.get(i), vos);
            // 审批人姓名
            SysUser approver = sysUserMapper.selectById(vos.getApproverId());
            vos.setApproverName(approver == null ? "该用户不存在" : approver.getName());
            // 获取审批人所在部门
            Organization organization = organizationMapper.selectById(vos.getApproveOrganizationId());
            vos.setApproveOrganizationName(organization == null ? "该部门已被删除" : organization.getName());

            voList.add(vos);
        }
        return voList;
    }
}
